<script setup>
import { ref } from 'vue'
import { addItemCategoryService, updateItemCategoryService } from '@/api/item.js'

// 控制对话框的显示与隐藏
const visibleDialog = ref(false)

const defaultDTO = {
  itemCategoryName: null
}

const itemCategoryDTO = ref({ ...defaultDTO })

// 向外暴露方法
const open = (row) => {
  visibleDialog.value = true // 打开对话框
  if (row.id) {
    itemCategoryDTO.value = {
      id: row.id,
      itemCategoryName: row.name
    }
  } else {
    itemCategoryDTO.value = { ...defaultDTO }
  }
}

// 提交逻辑
const emit = defineEmits(['success'])
const handleSubmit = async () => {
  if (itemCategoryDTO.value.id) {
    await updateItemCategoryService(itemCategoryDTO.value)
    ElNotification({
      title: '修改成功',
      type: 'success'
    })
    visibleDialog.value = false
  } else {
    await addItemCategoryService(itemCategoryDTO.value.itemCategoryName)
    ElNotification({
      title: '新增成功',
      type: 'success'
    })
    visibleDialog.value = false
  }
  emit('success')
}

// 取消逻辑
const handleCancel = () => {
  visibleDialog.value = false
  itemCategoryDTO.value = { ...defaultDTO }
}

defineExpose({
  open
})
</script>

<template>
  <!-- 对话框 -->
  <el-dialog
    v-model="visibleDialog"
    :title="itemCategoryDTO.id ? '修改物品类别' : '新增物品类别'"
    width="500"
  >
    <el-form :model="itemCategoryDTO" ref="formRef" label-width="auto">
      <el-form-item label="物品类别名称" prop="itemCategoryName">
        <el-input
          v-model="itemCategoryDTO.itemCategoryName"
          placeholder="请输入物品类别名称"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button plain @click="handleCancel">取消</el-button>
        <el-button type="primary" plain @click="handleSubmit">提交</el-button>
      </div>
    </template>
  </el-dialog>
</template>
